package com.wys.proxydemo.cglib;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author godShan
 * @Description:
 * @date 2019/5/6 13:30
 */
public class CglibProxy implements MethodInterceptor {


    public Object getInstance(Object obj) {
        Class<?> clazz = obj.getClass();
        //enhancer 相当于proxy 的代理工具类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object obj = methodProxy.invokeSuper(o, objects);
        after();
        return obj;
    }

    private void after() {
        System.out.println("客官您慢点，您的菜马上就到！");
    }

    private void before() {
        System.out.println("请问客官您需要点什么？小店所有菜系色香味俱全！");
    }
}
